﻿using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using com.IronOne.BoardPACWinApp.Common;
using com.IronOne.BoardPACWinApp.Helpers;
using com.IronOne.BoardPACWinApp.ViewModel;
using com.IronOne.BoardPACWinAppBO.General;
using com.IronOne.BoardPACWinAppService.Agenda;
using com.IronOne.BoardPACWinAppUtil.Util;
using GalaSoft.MvvmLight.Messaging;

namespace com.IronOne.BoardPACWinApp.View.Page
{
    public sealed partial class AddCommentsPage
    {
        private const int AnimeTime = 500;
        //int _PasswordAttempts = 25;
        //int PdfViewerBorder = 70;
        private const double PanelPropotion = 0.25;
        private IDialogService _dialogService;
        public bool IsCollapsed;
        private readonly IAgendaService _agendaService;

        public AddCommentsPage()
        {
            InitializeComponent();
            NavigationHelper = new NavigationHelper(this);
            //this.navigationHelper.LoadState += navigationHelper_LoadState;
            //this.navigationHelper.SaveState += navigationHelper_SaveState;

            _dialogService = new DialogService();
            _agendaService = new AgendaService();

            AddCommentsViewModel.SubscribeToNewlyAddedComment<string>(ScrollToItem);
            AddCommentsViewModel.ScrollToAddedCommentEvt += (ScrollToItem);
        }

        /// <summary>
        ///     NavigationHelper is used on each page to aid in navigation and
        ///     process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper { get; private set; }

        protected override async void HandleMessages(NotificationMessage<MessageDataModel> mdm)
        {
            base.HandleMessages(mdm);
            await BasePage.GetInstance().HandleMessages(mdm);
        }

        private async void ScrollToItem(string obj)
        {
            try
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    if (CommentsDetailView.Items != null && CommentsDetailView.Items.Count > 0)
                    {
                        CommentsDetailView.ScrollIntoView(CommentsDetailView.Items.Last());
                    }
                });
            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        ///     Populates the page with content passed during navigation.  Any saved state is also
        ///     provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">
        ///     The parameter value passed to
        ///     <see cref="Frame.Navigate(Type, Object)" /> when this page was initially requested.
        /// </param>
        /// <param name="pageState">
        ///     A dictionary of state preserved by this page during an earlier
        ///     session.  This will be null the first time a page is visited.
        /// </param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        ///     Preserves state associated with this page in case the application is suspended or the
        ///     page is discarded from the navigation cache.  Values must conform to the serialization
        ///     requirements of <see cref="SuspensionManager.SessionState" />.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedTo(e);
                NavigationHelper.OnNavigatedTo(e);

                ClearMembersAndClosePanel();

                //1 means Meeting Comments
                if (AddCommentsViewModel.CommentType == 1) return;

                var pModel = await _agendaService.GetPaperById(AddCommentsViewModel.AgendaItemId);

                var finalApprovalsbyBs = new List<byte> {1, 2, 3};
                var isFinalApprovalGiven = finalApprovalsbyBs.Contains(pModel.PaperStatus);

                AddCommentsGrd.Visibility = Visibility.Visible;
                if (isFinalApprovalGiven && !Global.IsBoardSecrartary)
                {
                    AddCommentsGrd.Visibility = Visibility.Collapsed;
                    await _dialogService.ShowMessage("Paper has finalized. You can not comment on this paper");
                }
            }
            catch (Exception)
            {
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            NavigationHelper.OnNavigatedFrom(e);
        }

        private async void Share_Btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SelectAllChk.IsChecked = false;

                if (String.IsNullOrWhiteSpace(TxbComment.Text.Trim()))
                {
                    await _dialogService.ShowMessage("Add a comment before share");
                    return;
                }

                OpenMembersPanel();
            }
            catch (Exception)
            {
            }
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            ClearMembersAndClosePanel();
        }

        private void Clear_Btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                TxbComment.Text = "";
                TxbComment.Focus(FocusState.Keyboard);
                SelectAllChk.IsChecked = false;

                if (!ShareBtn.IsEnabled)
                {
                    ClearMembersAndClosePanel();
                }
            }
            catch (Exception)
            {
            }
        }

        private void Ok_Btn_Click(object sender, RoutedEventArgs e)
        {
            IsCollapsed = true;
            CloseMemberPanel();
        }

        private void SelectAll_Btn_Click(object sender, RoutedEventArgs e)
        {
            if (SelectAllChk.IsChecked != null && (bool) SelectAllChk.IsChecked)
                SelectAllChk.IsChecked = false;
            else
                SelectAllChk.IsChecked = true;
        }

        private void SelectAll_Chk_Unchecked(object sender, RoutedEventArgs e)
        {
            ParticipantsListView.SelectedIndex = -1;
        }

        //private void SelectAll_txt_Tapped(object sender, TappedRoutedEventArgs e)
        //{
        //    if ((bool)SelectAll_Chk.IsChecked)
        //        SelectAll_Chk.IsChecked = false;
        //    else
        //        SelectAll_Chk.IsChecked = true;
        //}

        private void pageRoot_Unloaded(object sender, RoutedEventArgs e)
        {
            _dialogService = null;
        }

        private void OpenMembersPanel()
        {
            try
            {
                ShareBtn.IsEnabled = false;
                double val = (int) (Window.Current.Bounds.Width * PanelPropotion);
                if (val < Utility.GetFlyoutDefaultWidth()) val = Utility.GetFlyoutDefaultWidth();

                var storyboard = new Storyboard();
                var duration = new Duration(TimeSpan.FromMilliseconds(AnimeTime));
                var ease = new CubicEase {EasingMode = EasingMode.EaseOut};

                var animation = new DoubleAnimation {EasingFunction = ease, Duration = duration};
                storyboard.Children.Add(animation);
                animation.From = 0;
                animation.To = val;
                animation.EnableDependentAnimation = true;
                Storyboard.SetTarget(animation, MemberPanelGrd);
                Storyboard.SetTargetProperty(animation, "(ColumnDefinition.MaxWidth)");
                storyboard.Begin();
            }
            catch (Exception)
            {
            }
        }

        private void CloseMemberPanel()
        {
            try
            {
                ShareBtn.IsEnabled = true;
                double val = (int) (Window.Current.Bounds.Width*PanelPropotion);

                var storyboard = new Storyboard();
                var duration = new Duration(TimeSpan.FromMilliseconds(AnimeTime));
                var ease = new CubicEase {EasingMode = EasingMode.EaseOut};

                var animation = new DoubleAnimation {EasingFunction = ease, Duration = duration};
                storyboard.Children.Add(animation);
                animation.From = val;
                animation.To = 0;
                animation.EnableDependentAnimation = true;
                Storyboard.SetTarget(animation, MemberPanelGrd);
                Storyboard.SetTargetProperty(animation, "(ColumnDefinition.MaxWidth)");
                storyboard.Begin();
            }
            catch (Exception)
            {
            }
        }

        private void ClearMembersAndClosePanel()
        {
            SelectAllChk.IsChecked = false;
            CloseMemberPanel();
        }
    }
}